package org.kumas.sgrpc.common.extension.factory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ServiceLoader;

import org.kumas.sgrpc.common.extension.Adaptive;
import org.kumas.sgrpc.common.extension.ExtensionFactory;
import org.kumas.sgrpc.common.extension.ExtensionLoader;

@Adaptive
public class AdaptiveExtensionFactory implements ExtensionFactory {

    private static final List<ExtensionFactory> factories;

    static {
        List<ExtensionFactory> list = new ArrayList<ExtensionFactory>();
        ServiceLoader<ExtensionFactory> loadedCls = ServiceLoader.load(ExtensionFactory.class);
        for (ExtensionFactory s : loadedCls) {
            list.add(s);
        }

        factories = Collections.unmodifiableList(list);
    }

    @Override
    public <T> T getExtension(Class<T> type, String name) {
        for (ExtensionFactory factory : factories) {
            T extension = factory.getExtension(type, name);
            if (extension != null) {
                return extension;
            }
        }
        return null;
    }

}